<template>
  <div
    class="dioa-center flex items-center w-full h-31 border border-neutral-30 py-8 px-10 justify-between rounded-lg"
  >
    <div class="dioa-center flex justify-center items-center">
      <div class="dioa-box">
        <div class="dioa-box font-medium text-2xl">
          <h1 class="title">发票头管理</h1>
        </div>
        <p class="dioa-text"></p>
      </div>
    </div>
    <div class="dioa-center flex justify-center items-center space-x-5">
      <router-link to="/user/IssuingReceipt">
        <button
          type="button"
          class="dioa-button__root inline-flex appearance-none items-center justify-center select-none relative whitespace-nowrap align-middle transition outline-none cursor-pointer disabled:cursor-not-allowed h-10 px-5 text-base font-medium text-black bg-neutral-30 hover:bg-neutral-40 active:bg-black active:text-white disabled:text-neutral-40 disabled:bg-neutral-30 data-loading:text-transparent data-loading:bg-neutral-30 rounded-full border-0"
        >
          返回发票中心
        </button>
      </router-link>

      <button
        type="button"
        @click="addOrupdateTicketHeader(0)"
        class="dioa-button__root inline-flex appearance-none items-center justify-center select-none relative whitespace-nowrap align-middle transition outline-none cursor-pointer disabled:cursor-not-allowed h-10 px-5 text-base font-medium text-white bg-red hover:bg-neutral-60 active:bg-black disabled:bg-neutral-40 data-loading:text-transparent data-loading:bg-neutral-40 rounded-full border-0"
      >
        新增
      </button>
    </div>
  </div>
  <!--  -->
  <div style="height: 20px"></div>
  <MyTable :tableData="ticketTopList" :columns="titleData">
    <template #fordata="{ row }">
      <!-- 自定义单元格内容 -->
      <!-- {{ row }} -->
      <el-button
        size="small"
        class="custom-button"
        @click="addOrupdateTicketHeader(1, row)"
        >修改</el-button
      >
      <el-button size="small" @click="delticketHeader(row)">删除</el-button>
    </template>
  </MyTable>
  <MyDialog @update:visible="updateDialog" :initVisible="dialogVisible" :width="1000">
    <div class="formLayer">
      <h3 class="title">
        {{ edit ? "编辑" : "填写" }}发票信息
        <el-button size="small" circle @click="handleClose"
          ><el-icon><CloseBold /></el-icon
        ></el-button>
      </h3>
      <form class="dioa-form__form block w-full" ref="form" :model="formdata">
        <div class="dioa-box space-y-10">
          <div
            class="dioa-form__control grid gap-x-3 gap-y-2 data-orientation-h:grid-rows-[auto_auto] data-orientation-h:grid-cols-[min-content_auto]"
          >
            <label
              class="dioa-form__label flex items-center w-max shrink-0 text-base col-span-1 data-orientation-h:row-start-1 data-orientation-h:col-start-1 text-neutral-60"
              >* &nbsp;
              <div class="dioa-box">默认开票信息</div></label
            >
            <div role="radiogroup" class="dioa-radio__group grid gap-6 grid-flow-col">
              <div class="dioa-center flex items-center space-x-6 justify-start">
                <el-radio v-model="formdata.isDefault" label="Y">是</el-radio>
                <el-radio v-model="formdata.isDefault" label="N">否</el-radio>
              </div>
            </div>
          </div>
          <div
            class="dioa-form__control grid gap-x-3 gap-y-2 data-orientation-h:grid-rows-[auto_auto] data-orientation-h:grid-cols-[min-content_auto]"
          >
            <label
              class="dioa-form__label flex items-center w-max shrink-0 text-base col-span-1 data-orientation-h:row-start-1 data-orientation-h:col-start-1 text-neutral-60"
              >* &nbsp;
              <div class="dioa-box">发票类型</div></label
            >
            <div role="radiogroup" class="dioa-radio__group grid gap-6 grid-flow-col">
              <div class="dioa-center flex items-center space-x-6 justify-start">
                <el-radio v-model="formdata.fpType" label="普票">普票</el-radio>
                <el-radio v-model="formdata.fpType" label="专票">专票</el-radio>
              </div>
            </div>
          </div>
          <div
            class="dioa-form__control grid gap-x-3 gap-y-2 data-orientation-h:grid-rows-[auto_auto] data-orientation-h:grid-cols-[min-content_auto]"
          >
            <label
              class="dioa-form__label flex items-center w-max shrink-0 text-base col-span-1 data-orientation-h:row-start-1 data-orientation-h:col-start-1 text-neutral-60"
              >* &nbsp;
              <div class="dioa-box">抬头类型</div></label
            >
            <div role="radiogroup" class="dioa-radio__group grid gap-6 grid-flow-col">
              <div class="dioa-center flex items-center space-x-6 justify-start">
                <el-radio v-model="formdata.ttType" label="企业">企业</el-radio>
                <el-radio v-model="formdata.ttType" label="个人">个人</el-radio>
              </div>
            </div>
          </div>

          <div
            class="dioa-form__control grid gap-x-3 gap-y-2 data-orientation-h:grid-rows-[auto_auto] data-orientation-h:grid-cols-[min-content_auto]"
          >
            <label
              class="dioa-form__label flex items-center w-max shrink-0 text-base col-span-1 data-orientation-h:row-start-1 data-orientation-h:col-start-1 text-neutral-60"
              id="formcontrol::rh::label"
              for="formcontrol::rh::field"
              data-orientation="vertical"
              >* &nbsp;
              <div class="dioa-box">发票抬头</div></label
            >
            <el-input v-model="formdata.fpTitel" placeholder="请输入"></el-input>
          </div>
          <div
            class="dioa-form__control grid gap-x-3 gap-y-2 data-orientation-h:grid-rows-[auto_auto] data-orientation-h:grid-cols-[min-content_auto]"
            id="formcontrol::rk:"
            v-if="formdata.ttType == '企业'"
          >
            <label
              class="dioa-form__label flex items-center w-max shrink-0 text-base col-span-1 data-orientation-h:row-start-1 data-orientation-h:col-start-1 text-neutral-60"
            >
              * &nbsp;
              <div class="dioa-box">企业税号</div></label
            >
            <el-input v-model="formdata.dutyParagraph" placeholder="请输入"></el-input>
          </div>
          <div
            class="dioa-form__control grid gap-x-3 gap-y-2 data-orientation-h:grid-rows-[auto_auto] data-orientation-h:grid-cols-[min-content_auto]"
          >
            <label
              class="dioa-form__label flex items-center w-max shrink-0 text-base col-span-1 data-orientation-h:row-start-1 data-orientation-h:col-start-1 text-neutral-60"
              >* &nbsp;
              <div class="dioa-box">电子邮箱</div></label
            >
            <el-input
              v-model="formdata.emailOrPhone"
              placeholder="发票成功开具后将通过邮件发送给您，且仅发送一次，请您准确输入电子邮箱"
            ></el-input>
          </div>
        </div>
        <div class="dioa-center flex justify-center items-center">
          <button
            type="button"
            @click="postData"
            class="mt-12 dioa-button__root inline-flex appearance-none items-center justify-center select-none relative whitespace-nowrap align-middle transition outline-none cursor-pointer disabled:cursor-not-allowed data-loading:text-transparent h-14 px-10 text-lg font-medium text-white bg-red hover:bg-neutral-60 active:bg-black disabled:bg-neutral-40 rounded-full border-0 w-full"
          >
            提交
          </button>
        </div>
      </form>
    </div>
  </MyDialog>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import MyDialog from "@/components/MyDialog.vue";
import MyTable from "@/components/MyTable.vue";
import { defineProps, defineEmits } from "vue";
import { ticketTopProps } from "@/common/utils/userType";
import {
  getinvoicelist,
  invoiceadd,
  invoiceupdate,
  removeInvoice,
} from "@/common/userApi";
import { ElMessage, ElMessageBox } from "element-plus";
const props = defineProps<{
  changeValue: (newValue: number) => void;
}>();

const emit = defineEmits(["updateValue"]);

const changeValue = () => {
  props.changeValue(3);
};
changeValue();

// 获取发票头列表
const ticketTopList = ref<ticketTopProps[] | any>([]);
const titleData = [
  { label: "发票类型", prop: "fpType", width: 120 },
  { label: "抬头类型", prop: "ttType", width: 120 },
  { label: "发票抬头", prop: "fpTitel" },
  { label: "操作", type: "template", width: 200 },
];

const invoicelist = () => {
  let data = reactive({
    pageNum: 1,
    pageSize: 100,
  });
  getinvoicelist(data).then((res) => {
    ticketTopList.value = res.data;
  });
};
// 初始化数据
invoicelist();
// 下面两个方法是发票弹窗对应的事件
const dialogVisible = ref(false);
const updateDialog = (value: boolean) => {
  dialogVisible.value = value;
};
const handleClose = () => {
  dialogVisible.value = false;
  // receiveData.value = [];
};
// 新增发票头
const formdata = reactive<ticketTopProps>({
  fpTitel: "",
  memberName: "",
  companyName: "",
  fpType: "普票", //发票类型（普票，专票）
  ttType: "企业", //抬头类型（企业、个人）
  isDefault: "N", //是否默认(Y:是，N：否)
  emailOrPhone: "",
  dutyParagraph: "",
});
const edit = ref(false);
const addOrupdateTicketHeader = (id: number, row?: ticketTopProps) => {
  // 新增invoiceadd  修改invoiceupdate
  // console.log(formdata);
  if (id == 0) {
    edit.value = false;
  } else if (id == 1) {
    edit.value = true;
  }
  dialogVisible.value = true;
  if (row) {
    formdata.fpTitel = row.fpTitel;
    formdata.memberName = row.memberName;
    formdata.companyName = row.companyName;
    formdata.fpType = row.fpType;
    formdata.ttType = row.ttType;
    formdata.isDefault = row.isDefault;
    formdata.emailOrPhone = row.emailOrPhone;
    formdata.dutyParagraph = row.dutyParagraph;
  }
};
const postData = () => {
  if (formdata.fpTitel == "") {
    ElMessage.error("请输入发票抬头");
    return;
  } else {
    if (formdata.ttType == "企业") {
      formdata.companyName = formdata.ttType;
      formdata.memberName = "";
    }
    if (formdata.ttType == "个人") {
      formdata.memberName = formdata.ttType;
      formdata.companyName = "";
    }
  }
  if (formdata.ttType == "企业" && formdata.dutyParagraph == "") {
    ElMessage.error("请输入税号");
    return;
  }
  if (formdata.emailOrPhone == "") {
    ElMessage.error("请输入邮箱");
    return;
  } else {
    const emailRegex = /^[\u4e00-\u9fa5a-zA-Z\d]+([-_.][\u4e00-\u9fa5A-Za-z\d]+)*@([\u4e00-\u9fa5A-Za-z\d]+[-.]){1,2}[\u4e00-\u9fa5A-Za-z\d]{2,5}$/g;
    if (!emailRegex.test(formdata.emailOrPhone)) {
      ElMessage.error("请输入正确的邮箱");
    }
  }

  // 新增invoiceadd  修改invoiceupdate
  if (!edit.value) {
    invoiceadd(formdata).then((res) => {
      if (res.code == 200) {
        ElMessage({
          message: "新增成功",
          type: "success",
        });
        handleClose();
      } else {
        ElMessage.error(res.msg);
      }
    });
  } else {
    invoiceupdate(formdata).then((res) => {
      // console.log(res);
      if (res.code == 200) {
        ElMessage({
          message: "修改成功",
          type: "success",
        });
        handleClose();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }
};
// 删除发票头
const delticketHeader = (row: ticketTopProps) => {
  // removeInvoice
  // console.log(row.id);
  ElMessageBox.confirm("请确定要删除吗?", "提示", {
    confirmButtonText: "是的",
    cancelButtonText: "取消",
    type: "Warning",
  })
    .then(() =>
      removeInvoice(row.id).then((res) => {
        if (res.code == 200) {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          invoicelist();
        }
      })
    )
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};
</script>
<style lang="scss">
.formLayer {
  padding: 20px;
  .title {
    display: flex;
    justify-content: space-between;
    font-size: 20px;
    font-weight: bold;
    text-align: center;
  }
  .dioa-form__form {
    margin-top: 50px;
  }
}
.el-radio__input.is-checked + .el-radio__label {
  color: #dd1a20 !important;
}
.el-radio__input.is-checked .el-radio__inner {
  background: #dd1a20 !important;
  border-color: #dd1a20 !important;
}

/* 覆盖Element UI默认的按钮颜色 */
.el-message-box .el-button {
  background-color: #dd1a20; /* 你想要的任何颜色 */
  border-color: #dd1a20;
}
</style>
